<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_User_Token extends ORM
{
    protected $_reload_on_wakeup = false;
    
    protected $_user = null;
    
	/**
	 * Handles garbage collection and deleting of expired objects.
	 *
	 * @return  void
	 */
	public function __construct($id = NULL)
	{
		parent::__construct($id);

		if (mt_rand(1, 100) === 1) {
			// Do garbage collection
			$this->delete_expired();
		}

		if ($this->expires < time() && $this->loaded()) { //$this->_loaded) {
			// This object has expired
			$this->delete();
		}
	}

	/**
	 * Deletes all expired tokens.
	 *
	 * @return  ORM
	 */
	public function delete_expired()
	{
		// Delete all expired tokens
		DB::delete($this->_table_name)
			->where('expires', '<', time())
			->execute($this->_db);

		return $this;
	}

	public function create(Validation $validation = null)
	{
		$this->token = $this->create_token();

		return parent::create($validation);
	}

	protected function create_token()
	{
		do {
			$token = sha1(uniqid(Text::random('alnum', 32), TRUE));
		}
		while(ORM::factory('user_token', array('token' => $token))->loaded());

		return $token;
	}
    
    /**
     * 
     */
    public function get_user()
    {
        if ($this->_user) {
            return $this->_user;
        }
        $user = ORM::factory('user', $this->user_id);
        $this->_user = $user;
        return $user;
    }

}